package com.whale.cloud.util.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.whale.cloud.util.StringUtils;
import com.whale.cloud.util.oss.OssProperties;
import lombok.extern.log4j.Log4j2;

import java.io.*;
import java.net.URL;
import java.util.Date;

/** Created by whale_xdl on 2017/7/11. */
@Log4j2
public class OssClient {

  private OssProperties ossProperties;

  private OSSClient ossClient;

  public void setOssProperties(OssProperties ossProperties) {
    this.ossProperties = ossProperties;
  }

  //获取OSSClient
  public void init() {
    ClientConfiguration conf = new ClientConfiguration(); // 创建ClientConfiguration实例
    conf.setMaxConnections(2000); // 设置OSSClient使用的最大连接数，默认1024
    conf.setSocketTimeout(10000); // 设置请求超时时间，默认50秒
    conf.setMaxErrorRetry(5); // 设置失败请求重试次数，默认3次
      log.debug("---->oss init:"+ossProperties.getBucket()+","+ossProperties.getAccessId()+","+ossProperties.getAccessKey());
    ossClient =
        new OSSClient(
            ossProperties.getEndpoint(),
            ossProperties.getAccessId(),
            ossProperties.getAccessKey(),
            conf); // 创建OSSClient实例*/
    // 使用访问OSS
    boolean exists = ossClient.doesBucketExist(ossProperties.getBucket()); //判断该Bucket是否已存在
    if (!exists) {
      ossClient.createBucket(ossProperties.getBucket()); //创建一个存储空间(Bucket)
      ossClient.setBucketAcl(
          ossProperties.getBucket(), CannedAccessControlList.PublicReadWrite); //设置bucket权限
//      SetBucketLifecycleRequest request =
//          new SetBucketLifecycleRequest(ossProperties.getBucket()); //设置生命周期规则
//      try {
//        request.AddLifecycleRule(
//            new LifecycleRule(
//                "ruleId1",
//                "matchPrefix1",
//                LifecycleRule.RuleStatus.Enabled,
//                DateUtil.parseIso8601Date("2122-10-12T00:00:00.000Z")));
//      } catch (Exception e) {
//        e.printStackTrace();
//      }
//      ossClient.setBucketLifecycle(request);
    }
  }

  //上传网络流
  public boolean passURL(String urlstr, String dirpath, String yourKey) {
    ObjectMetadata meta = new ObjectMetadata();
    meta.setCacheControl("no-cache");
    meta.setContentType("image/jpeg");
    meta.setContentDisposition("inline;filename=" + yourKey);
    InputStream inputStream;
    try {
      inputStream = new URL(urlstr).openStream();
      if (ossClient == null) init();
      ossClient.putObject(ossProperties.getBucket(), dirpath + yourKey, inputStream, meta);
      if (inputStream != null) {
        inputStream.close();
      }
      return true;
    } catch (Exception e) {
      destory(); // 关闭client
      log.error("Error Message: " + e.getMessage());
    }

    return false;
  }

  public boolean passFileStrem(String yourKey, String dirpath, InputStream fis) {
    if (ossClient == null) init();
    boolean bool = true;
    try {
      ossClient.putObject(ossProperties.getBucket(), dirpath + yourKey, fis);
      //            boolean found = ossClient.doesObjectExist(bucketName,dir+yourKey);
      //            if(!found){
      //                ossClient.putObject(bucketName, dir+yourKey, fis);
      //            }
    } catch (Exception e) {
      bool = false;
      destory(); //异常关闭
    }

    return bool;
  }

  //上传文件流
  public boolean passFileStrem(String yourKey, String dirpath, String filename) {
    if (ossClient == null) init();
    boolean bool = true;
    try {
      InputStream inputStream = new FileInputStream(filename);
      ossClient.putObject(ossProperties.getBucket(), dirpath + yourKey, inputStream);
      //            boolean found = ossClient.doesObjectExist(bucketName,dirpath+yourKey);
      //            if(!found){
      //                ossClient.putObject(bucketName, dirpath+yourKey, inputStream);
      //            }
    } catch (IOException e) {
      bool = false;
      destory();
    }

    return bool;
  }

  //流式下载
  public String ossDownObject(String yourKey) throws IOException { //bucketName="bucket_xdl"
    if (ossClient == null) init();
    ObjectListing objectListing = ossClient.listObjects(ossProperties.bucket);
    for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
      log.info(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
    }
    boolean exists = ossClient.doesBucketExist(ossProperties.bucket); //判断该Bucket是否已存在
    if (!exists) {
      return "Bucket不存在";
    }
    OSSObject ossObject = ossClient.getObject(ossProperties.bucket, yourKey);
    InputStream content = ossObject.getObjectContent();
    StringBuffer sb = new StringBuffer();
    if (content != null) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(content));
      while (true) {
        String line = reader.readLine();
        if (line == null) break;
        sb.append(line);
        log.info("\n" + line);
      }
      content.close();
    }
    destory();
    return sb.toString();
  }

  //下载到本地
  public void ossDownLocal(String yourKey, String yourLocalFile) {
    if (ossClient == null) init();

    ossClient.getObject(
        new GetObjectRequest(ossProperties.bucket, yourKey), new File(yourLocalFile));

    destory();
  }

  //销毁
  public void destory() {
    if (ossClient != null) {
      ossClient.shutdown();
      ossClient = null;
    }
  }

  //获取Url
  protected String getUrl(String youKey) {
    if (ossClient == null) init();
    Date expiration =
        new Date(
            new Date().getTime()
                + 3600l * 1000 * 24 * 365 * 10); // 设置URL过期时间为10年  3600l* 1000*24*365*10
    URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), youKey, expiration); // 生成URL

    //去掉url中的签名
    if (url != null) {
      return url.getProtocol() + "://" + url.getAuthority() + url.getPath(); //协议+""+授权部分+路径部分
    }

    return null;
  }
  //获取图片的url 地址后面有
  public String getImgUrl(String fileUrl, String dir) {
    if (StringUtils.isNotNull(fileUrl)) {
      String[] split = fileUrl.split("/");
      return getUrl(dir + split[split.length - 1]);
    }
    return null;
  }

  //获取图片的url 地址后面有
  public String getFileUrl(String dirpath, String fileUrl) {
    return getUrl(dirpath + fileUrl);
  }

  /**
   * 删除文件资源
   * @param diskName 文件路径
   * @param key 文件存储key
   */
  public void deleteFile(String diskName, String key) {
    if (ossClient == null) init();
    ossClient.deleteObject(ossProperties.bucket, diskName + key);
    log.debug("---->oss 删除成功" + diskName + "," + key);
  }

  /**
   * 资源是否存在
   * @param dirpath
   * @param yourKey
   * @return
   */
  public boolean existObject(String dirpath, String yourKey){
    if (ossClient == null) init();
    return ossClient.doesObjectExist(ossProperties.getBucket(),dirpath+yourKey);
  }
}
